home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 516 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  54 lines

  1. Path: news.sprintlink.net!datalytics!news
  2. From: Rob Stewart <stew@datalytics.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: beginner question - constants
  5. Date: 4 Jan 1996 21:25:27 GMT
  6. Organization: Datalytics, Inc
  7. Message-ID: <4chgk7$ldg@gold.datalytics.com>
  8. References: <4ceht0$ruj@sun.cis.smu.edu>
  9. NNTP-Posting-Host: pc071.datalytics.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=iso-8859-1
  12. Content-Transfer-Encoding: 8bit
  13. X-Mailer: Mozilla 1.22 (Windows; I; 32bit)
  14.  
  15. dbowman@post.smu.edu (Damon Bowman) wrote:
  16. >
  17. >Can anyone explain to me the functional difference between a
  18. >macro-based constant and a formal constant?  I understand that by
  19. >using the #define directive, the preprocessor replaces all instances
  20. >of the constant in the code with itÆs value.  I also understand that
  21. >formal constants (using the const keyword) do not undergo this
  22. >replacement.
  23. >
  24. >What I donÆt understand is why one might be better than another and
  25. >what conditions might influence me to choose one over the other.  They
  26. >appear to be two versions of the same thing.
  27. >
  28.  
  29. The difference is one of type safety.  When the preprocessor 
  30. makes a textual substitution, there is no type associated with 
  31. it (unless it happens to be something like 1.0f).  The 
  32. compiler can interpret that string as anything it likes in 
  33. each context.  A const variable has type and only allows the 
  34. compiler to perform implicit conversions appropriate to that 
  35. type.
  36.  
  37. To overcome this, some C programmers write manifest constants 
  38. (those declared with the #define directive) with type 
  39. information in a cast:
  40.  
  41. #define LOW_VALUE (unsigned short)1
  42.  
  43. This effects the same thing as the simpler:
  44.  
  45. const unsigned short LOW_VALUE = 1;
  46.  
  47. -- 
  48. Robert Stewart        | My opinions are usually my own.
  49. Datalytics, Inc.
  50. (513)226-7700
  51. stew@datalytics.com
  52.  
  53.  
  54.